//index.js
//获取应用实例
var app = getApp()
var admin_id = app.globalData.admin_id;
var cat_id = 0;
var share = app.globalData.share;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        currentIndex: 0,
        selectAllStatus: false,
        numbers: 1,//商品数量
        goods: [],
        total: '0.00',//总价
        allname: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },


    // 支付函数
    formSubmits: function (e) {
        var that = this;
		
        if (this.data.total != 0) {
            // this.formSubmit(e);
			app.globalData.goods_info = that.data.arr
			wx.navigateTo({
				url: '../../pages/pay/pay',
			})
			app.checkUser(app.globalData.openid, that, function () {
				wx.reLaunch({
					url: '../../pages/reg/reg',
				})
			})
        }
        else {
            wx.showToast({
                title: '无选择商品',
            })
        }

    },
    //计算当前时间
    getNowFormatDate: function () {
        var date = new Date();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + month + strDate + date.getHours() + date.getMinutes() + date.getSeconds();
        return currentdate;
    },
    //累加名称（暂时没有用到）
    addname: function () {
        var that = this;
        var allname = '';
        for (var i = 0; i < that.data.goods.length; i++) {
            if (that.data.goods[i].selected) {
                var onename = that.data.goods[i].goods_name + '*' + that.data.goods[i].numbers;
                allname += onename;
            }
        }
        that.setData({
            allname: allname
        })
        this.addArr();
    },
    getFloatStr: function (num) {
        num += '';
        num = num.replace(/[^0-9|\.]/g, '');
        if (/^0 + /)
            num = num.replace(/^0+/, '');
        if (!/\./.test(num))
            num += '.00';
        if (/^\./.test(num))
            num = '0' + num;
        num += '00';
        num = num.match(/\d+\.\d{2}/)[0];
        return num;
    },
    // 添加购物车数组
    addArr: function () {
        var that = this;
        var arr = [];

        for (var i = 0; i < that.data.goods.length; i++) {
            if (that.data.goods[i].selected) {
                var o = new Object();
                o.goods_name = that.data.goods[i].goods_name;
                o.goods_id = that.data.goods[i].goods_id;
                o.num = that.data.goods[i].numbers;
				o.shop_price = that.data.goods[i].shop_price;
                o.order_sn = that.getNowFormatDate();
				o.spe = that.data.goods[i].spec_key_name;
				o.original_img = that.data.goods[i].original_img;
                arr.push(o);
            }
        }
        that.setData({
            arr: arr
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var that = this;
        var openid = app.globalData.openid;

        wx.request({
            url: 'https://xcxu.we-fs.com/index.php/api/goods/cartinfo?admin_id=' + admin_id + '&openid=' + openid,
            success: function (e) {
                console.log(e)
                if(e.data == ''){
                    that.setData({
                        goods: [],
                        isnull: true
                    })
                    return false;
                }
                that.setData({
                    goods: e.data.result
                })
                for (var i = 0; i < that.data.goods.length; i++) {
                    that.data.goods[i].selected = false;
                    that.data.goods[i].numbers = 1;
                }
                that.setData({
                    goods: that.data.goods,
                    total: '0.00',
                    isnull: false
                })

            }
        })
    },
    //加号按钮,.增加商品
    addCount: function (e) {
        var index = e.currentTarget.dataset.index;
        this.data.goods[index].numbers++;
        this.setData({
            goods: this.data.goods
        })
        this.calTotal();
    },
    delGoods: function (e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        wx.showModal({
            title: '提示',
            content: '是否删除?',
            success: function (e) {
                console.log(e)
                if (e.confirm) {
                    wx.request({
                        url: 'https://xcxu.we-fs.com/index.php/api/goods/cart?id=' + that.data.goods[index].catid,
                        success: function (re) {
                            that.data.goods.splice(index, 1);
                            console.log(that.data.goods);
                            that.setData({
                                goods: that.data.goods
                            })
                            console.log('删除成功');
                        }
                    })
                }
            }
        })

    },
    //减号按钮，减少商品
    reduceCount: function (e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        if (this.data.goods[index].numbers < 2) {
            return false;
        }
        this.data.goods[index].numbers--;
        this.setData({
            goods: this.data.goods
        })
        this.calTotal();
    },

    //计算总价
    calTotal: function (e) {
        var that = this;
        var total = 0;
        for (var i = 0; i < that.data.goods.length; i++) {
            if (that.data.goods[i].selected == true) {
                total += that.data.goods[i].shop_price * that.data.goods[i].numbers;
            }
        }
        that.setData({
            total: that.getFloatStr(total)
        })
		this.addname();
    },
    //全选
    selectAll: function (e) {
        let selectAllStatus = this.data.selectAllStatus;    // 是否全选状态
        selectAllStatus = !selectAllStatus;
        let goods = this.data.goods;

        for (let i = 0; i < goods.length; i++) {
            goods[i].selected = selectAllStatus;            // 改变所有商品状态
        }
        this.setData({
            selectAllStatus: selectAllStatus,
            goods: goods
        });
        this.calTotal();                              // 重新获取总价
    },
    //单选
    selectList: function (e) {
        const index = e.currentTarget.dataset.index;    // 获取data- 传进来的index
        let goods = this.data.goods;                    // 获取购物车列表
        const selected = goods[index].selected;         // 获取当前商品的选中状态
        goods[index].selected = !selected;              // 改变状态
        this.setData({
            goods: goods
        });
        this.calTotal();
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        return {
			title: share,
            path: 'pages/index/index'
        }
    },

    //支付函数
    formSubmit: function (e) {
        var thisNode = e.currentTarget.dataset;
        var that = this;

        var arr = that.data.arr;
        console.log('arr')
        console.log(arr)
        wx.login({
            success: function (res) {
                console.log("res.code=====" + res.code);
                if (res.code) {
                    //发起网络请求
                    wx.request({
                        url: 'https://xcxu.we-fs.com/index.php/api/goods/openid?code=' + res.code + '&appid=' + app.globalData.appid + '&secret=' + app.globalData.secret,
                        method: "GET",
                        success: function (re) {
                            
                            console.log(re.data)
                            wx.chooseAddress({
                                success: function (r) {
                                    var name = r.userName;
                                    var openid = re.data.openid;

                                    wx.request({
                                        url: 'https://xcxu.we-fs.com/index.php/api/goods/zhifus?name=' + name + '&sj=' + r.telNumber + '&openid=' + openid + '&price=' + thisNode.price + '&goods_name=' + thisNode.name + '&mch_id=' + app.globalData.mch + '&appid=' + app.globalData.appid,
                                        data: {},
                                        method: 'GET', 
                                        success: function (res) {
                                            console.log(res.data);
                                            console.log('rs====' + thisNode.price);
                                            console.log('支付====' + thisNode.name);
                                            console.log("************");
                                            console.log(res);
                                            console.log(openid)
                                            wx.requestPayment(
                                                {
                                                    'appId': app.globalData.appid,
                                                    'timeStamp': res.data.timeStamp,
                                                    'nonceStr': res.data.nonceStr,
                                                    'package': 'prepay_id=' + res.data.prepayid,
                                                    'signType': 'MD5',
                                                    'paySign': res.data.sign,
                                                    'success': function (res) {
                                                        for (var i = 0; i < arr.length; i++) {
                                                            wx.request({
                                                                url: 'https://xcxu.we-fs.com/index.php/api/goods/order1',
                                                                method: 'post',
                                                                data: {
                                                                    'name': name,
                                                                    'sj': r.telNumber,
                                                                    'dz': arr[i].des,
                                                                    'admin_id': admin_id,
                                                                    'goods_id': arr[i].goods_id,
                                                                    'goods_name': '【订单】' + arr[i].goods_name + "*" + arr[i].num,
                                                                    'num': arr[i].num,
                                                                    'price': arr[i].price * arr[i].num,
                                                                    'order_sn': arr[i].order_sn,
																	'openid': app.globalData.openid
                                                                },
                                                                header: {
                                                                    'content-type': 'application/x-www-form-urlencoded'
                                                                },
                                                                success: function (res) {
                                                                    that.setData({
                                                                        list: res.data[0],

                                                                    })
                                                                    setTimeout(function () {
                                                                        that.setData({
                                                                            loadingHidden: true
                                                                        })
                                                                    }, 1500)
                                                                }
                                                            })
                                                        }
                                                    },
                                                    'fail': function (res) {
                                                        console.log('失败！' + res.errMsg)
                                                    }
                                                })
                                        },
                                        fail: function () {
                                            // fail
                                        },
                                        complete: function () {
                                            // complete
                                        }
                                    })
                                }
                            })

                        }
                    })
                } else {
                    console.log('获取用户登录态失败！' + res.errMsg)
                }
            }
        });
    }
})
